<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="任务号" prop="pickTaskNo">
        <el-input v-model="queryParams.pickTaskNo" placeholder="请输入任务号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="波次号" prop="waveNo">
        <el-input v-model="queryParams.waveNo" placeholder="请输入波次号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="出库单号" prop="outboundOrderNo">
        <el-input v-model="queryParams.outboundOrderNo" placeholder="请输入出库单号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="状态" prop="taskStatus">
        <el-select v-model="queryParams.taskStatus" placeholder="请选择状态" clearable>
          <el-option label="待拣货" value="0" />
          <el-option label="拣货中" value="1" />
          <el-option label="已拣货" value="2" />
          <el-option label="异常" value="9" />
        </el-select>
      </el-form-item>
      <el-form-item label="拣货员" prop="picker">
        <el-select v-model="queryParams.picker" placeholder="请选择拣货员" clearable>
          <el-option v-for="user in userOptions" :key="user.value" :label="user.label" :value="user.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="queryParams.priority" placeholder="请选择优先级" clearable>
          <el-option label="高" value="high" />
          <el-option label="中" value="medium" />
          <el-option label="低" value="low" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="handleDateChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="mb8">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ statistics.totalTasks }}</div>
            <div class="stat-label">总任务数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-value pending">{{ statistics.pendingTasks }}</div>
            <div class="stat-label">待拣货</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-value processing">{{ statistics.processingTasks }}</div>
            <div class="stat-label">拣货中</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-value completed">{{ statistics.completedTasks }}</div>
            <div class="stat-label">已完成</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleCreate" v-hasPermi="['wms:pick:add']">创建任务</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-user" size="mini" :disabled="!multipleSelection.length" @click="handleBatchAssign" v-hasPermi="['wms:pick:edit']">批量分配</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-sort" size="mini" :disabled="!multipleSelection.length" @click="handleOptimizeRoute" v-hasPermi="['wms:pick:edit']">路径优化</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['wms:pick:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table 
      v-loading="loading" 
      :data="taskList" 
      border 
      stripe 
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
      :row-class-name="getRowClassName">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务号" align="center" prop="pickTaskNo" width="160" sortable="custom" />
      <el-table-column label="波次号" align="center" prop="waveNo" width="120" />
      <el-table-column label="出库单号" align="center" prop="outboundOrderNo" width="160" />
      <el-table-column label="商品信息" min-width="200">
        <template slot-scope="scope">
          <div class="product-info">
            <div class="product-name">{{ scope.row.productName }}</div>
            <div class="product-code">编码：{{ scope.row.productCode }}</div>
            <div class="product-spec">规格：{{ scope.row.productSpec || '-' }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="优先级" align="center" prop="priority" width="80">
        <template slot-scope="scope">
          <el-tag :type="getPriorityTag(scope.row.priority)" size="small">
            {{ getPriorityText(scope.row.priority) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="拣货进度" align="center" width="150">
        <template slot-scope="scope">
          <el-progress 
            :percentage="getProgress(scope.row)" 
            :status="getProgressStatus(scope.row)"
            :stroke-width="6"
            :show-text="false">
          </el-progress>
          <div class="progress-text">{{ scope.row.pickedQuantity || 0 }}/{{ scope.row.pickQuantity || 0 }}</div>
        </template>
      </el-table-column>
      <el-table-column label="储位" align="center" prop="locationCode" width="100" />
      <el-table-column label="拣货员" align="center" prop="picker" width="100" />
      <el-table-column label="状态" align="center" prop="taskStatus" width="100">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.taskStatus)" size="small">
            {{ getStatusText(scope.row.taskStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" sortable="custom" />
      <el-table-column label="操作" align="center" width="220" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)" v-hasPermi="['wms:pick:query']">详情</el-button>
          <el-button v-if="scope.row.taskStatus === '0'" size="mini" type="text" icon="el-icon-edit" @click="handleStartPick(scope.row)" v-hasPermi="['wms:pick:edit']">开始拣货</el-button>
          <el-button v-if="scope.row.taskStatus === '1'" size="mini" type="text" icon="el-icon-check" @click="handleComplete(scope.row)" v-hasPermi="['wms:pick:edit']">完成</el-button>
          <el-button v-if="scope.row.taskStatus === '0'" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['wms:pick:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>
  </div>
</template>

<script>
import { listPickTask, completePickTask, delPickTask } from '@/api/wms/pick'

export default {
  name: 'PickTask',
  data() {
    return {
      loading: true,
      showSearch: true,
      total: 0,
      taskList: [],
      multipleSelection: [],
      dateRange: [],
      userOptions: [
        { label: '张三', value: 'zhangsan' },
        { label: '李四', value: 'lisi' },
        { label: '王五', value: 'wangwu' }
      ],
      statistics: {
        totalTasks: 0,
        pendingTasks: 0,
        processingTasks: 0,
        completedTasks: 0
      },
      queryParams: { 
        pageNum: 1, 
        pageSize: 10, 
        pickTaskNo: null, 
        waveNo: null,
        outboundOrderNo: null,
        taskStatus: null,
        picker: null,
        priority: null,
        beginTime: null,
        endTime: null,
        orderByColumn: null,
        isAsc: null
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listPickTask(this.queryParams).then(response => {
        this.taskList = response.rows
        this.total = response.total
        this.loading = false
        this.getStatistics()
      }).catch(() => {
        this.loading = false
      })
    },

    getStatistics() {
      this.statistics.totalTasks = this.taskList.length
      this.statistics.pendingTasks = this.taskList.filter(item => item.taskStatus === '0').length
      this.statistics.processingTasks = this.taskList.filter(item => item.taskStatus === '1').length
      this.statistics.completedTasks = this.taskList.filter(item => item.taskStatus === '2').length
    },

    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    resetQuery() {
      this.resetForm('queryForm')
      this.dateRange = []
      this.queryParams.beginTime = null
      this.queryParams.endTime = null
      this.handleQuery()
    },

    handleDateChange(dates) {
      if (dates && dates.length === 2) {
        this.queryParams.beginTime = dates[0]
        this.queryParams.endTime = dates[1]
      } else {
        this.queryParams.beginTime = null
        this.queryParams.endTime = null
      }
    },

    handleSelectionChange(selection) {
      this.multipleSelection = selection
    },

    handleSortChange({ column, prop, order }) {
      this.queryParams.orderByColumn = prop
      this.queryParams.isAsc = order === 'ascending' ? 'asc' : 'desc'
      this.getList()
    },

    handleCreate() {
      this.$router.push('/wms/pick/create')
    },

    handleBatchAssign() {
      if (!this.multipleSelection.length) {
        this.$message.warning('请选择要分配的任务')
        return
      }
      this.$message.success('批量分配功能开发中...')
    },

    handleOptimizeRoute() {
      if (!this.multipleSelection.length) {
        this.$message.warning('请选择要优化的任务')
        return
      }
      this.$confirm('确认对选中的任务进行路径优化?', '提示', { type: 'warning' }).then(() => {
        this.$message.success('路径优化完成')
        this.getList()
      })
    },

    handleExport() {
      this.$confirm('确认导出所有拣货任务数据?', '提示', { type: 'warning' }).then(() => {
        this.$message.success('导出功能开发中...')
      })
    },

    handleDetail(row) {
      this.$router.push({
        path: '/wms/pick/detail/' + row.id
      })
    },

    handleStartPick(row) {
      this.$router.push({
        path: '/wms/pick/operation',
        query: { taskId: row.id }
      })
    },

    handleComplete(row) {
      this.$confirm('是否确认完成任务号为"' + row.pickTaskNo + '"的拣货任务？', '提示', { type: 'warning' }).then(() => {
        return completePickTask(row.id)
      }).then(() => {
        this.getList()
        this.$message.success('操作成功')
      })
    },

    handleDelete(row) {
      this.$confirm('是否确认删除任务号为"' + row.pickTaskNo + '"的数据项？', '提示', { type: 'warning' }).then(() => {
        return delPickTask(row.id)
      }).then(() => {
        this.getList()
        this.$message.success('删除成功')
      })
    },

    getStatusType(status) {
      const map = { '0': 'info', '1': 'warning', '2': 'success', '9': 'danger' }
      return map[status] || 'info'
    },

    getStatusText(status) {
      const map = { '0': '待拣货', '1': '拣货中', '2': '已拣货', '9': '异常' }
      return map[status] || status
    },

    getPriorityTag(priority) {
      return { 'high': 'danger', 'medium': 'warning', 'low': 'info' }[priority] || 'info'
    },

    getPriorityText(priority) {
      return { 'high': '高', 'medium': '中', 'low': '低' }[priority] || priority
    },

    getProgress(row) {
      if (!row.pickQuantity || row.pickQuantity === 0) return 0
      return Math.round((row.pickedQuantity || 0) / row.pickQuantity * 100)
    },

    getProgressStatus(row) {
      const progress = this.getProgress(row)
      if (progress === 100) return 'success'
      if (progress > 0) return 'active'
      return null
    },

    getRowClassName({ row }) {
      if (row.taskStatus === '9') return 'warning-row'
      if (row.priority === 'high') return 'high-priority-row'
      return ''
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.stat-card {
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-item {
  padding: 10px 0;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-value.pending {
  color: #909399;
}

.stat-value.processing {
  color: #E6A23C;
}

.stat-value.completed {
  color: #67C23A;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.product-info {
  line-height: 1.4;
}

.product-name {
  font-weight: bold;
  color: #303133;
  margin-bottom: 2px;
}

.product-code, .product-spec {
  font-size: 12px;
  color: #909399;
  margin-bottom: 1px;
}

.progress-text {
  font-size: 12px;
  color: #606266;
  margin-top: 2px;
}

.mb8 {
  margin-bottom: 8px;
}

/* 表格行样式 */
.el-table .warning-row {
  background: #fdf6ec;
}

.el-table .high-priority-row {
  background: #fef0f0;
}
</style>
